import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:app_links/app_links.dart';
import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../routes/app_navigator.dart';

class GroupInviteController extends GetxController {
  static GroupInviteController get to => Get.find();
  
  final _appLinks = AppLinks();
  StreamSubscription<Uri>? _linkSubscription;
  
  @override
  void onInit() {
    super.onInit();
    _initGroupInviteLinks();
  }
  
  @override
  void onClose() {
    _linkSubscription?.cancel();
    super.onClose();
  }
  
  /// 初始化群聊邀请链接监听
  void _initGroupInviteLinks() {
    // 监听app运行时的链接
    _linkSubscription = _appLinks.uriLinkStream.listen(
      (uri) {
        Logger.print('收到群聊邀请链接: $uri');
        _handleGroupInviteLink(uri);
      },
      onError: (err) {
        Logger.print('群聊邀请链接错误: $err');
      },
    );
    
    // 处理app启动时的链接
    _handleInitialInviteLink();
  }
  
  /// 处理app启动时的初始邀请链接
  Future<void> _handleInitialInviteLink() async {
    try {
      final uri = await _appLinks.getInitialLink();
      if (uri != null && _isGroupInviteLink(uri)) {
        Logger.print('启动时收到群聊邀请链接: $uri');
        await Future.delayed(const Duration(seconds: 2)); // 等待应用初始化完成
        _handleGroupInviteLink(uri);
      }
    } catch (err) {
      Logger.print('获取初始邀请链接失败: $err');
    }
  }
  
  /// 判断是否为群聊邀请链接
  bool _isGroupInviteLink(Uri uri) {
    return (uri.scheme == 'paxiy' && uri.host == 'group' && uri.path.startsWith('/invite')) ||
           (uri.scheme == 'https' && uri.host == 'paxiy.app' && uri.path.startsWith('/group/invite'));
  }
  
  /// 处理群聊邀请链接
  void _handleGroupInviteLink(Uri uri) {
    if (!_isGroupInviteLink(uri)) return;
    
    final queryParams = uri.queryParameters;
    final groupId = queryParams['groupId'];
    final inviteCode = queryParams['inviteCode'];
    final inviterUserId = queryParams['inviter'];
    
    if (groupId != null) {
      _processGroupInvite(
        groupId: groupId,
        inviteCode: inviteCode,
        inviterUserId: inviterUserId,
      );
    } else {
      IMViews.showToast('邀请链接格式错误');
    }
  }
  
  /// 处理群聊邀请逻辑
  Future<void> _processGroupInvite({
    required String groupId,
    String? inviteCode,
    String? inviterUserId,
  }) async {
    try {
      // 检查用户是否已登录
      if (!await _checkUserLogin()) {
        _showLoginRequiredDialog(groupId, inviteCode, inviterUserId);
        return;
      }
      
      // 获取群组信息
      final groupInfo = await _getGroupInfo(groupId);
      if (groupInfo == null) {
        IMViews.showToast('群组不存在或已解散');
        return;
      }
      
      // 检查用户是否已在群组中
      final isAlreadyMember = await _checkIfAlreadyMember(groupId);
      if (isAlreadyMember) {
        _showAlreadyMemberDialog(groupInfo);
        return;
      }
      
      // 检查是否需要支付进群费用
      final paymentInfo = await _checkGroupPaymentStatus(groupId);
      Logger.print('paymentInfo: $paymentInfo');
      if (paymentInfo['requiresPayment'] == true) {
        if (paymentInfo['hasPaid'] == true) {
          // 已支付，直接进入群聊
          _joinGroupDirectly(groupInfo);
        } else {
          // 未支付，跳转到支付页面
          _showPaymentPage(groupInfo, groupId, inviteCode, inviterUserId, paymentInfo['fee']);
        }
      } else {
        // 不需要支付，显示加入群组确认对话框
        _showJoinGroupDialog(
          groupInfo: groupInfo,
          inviteCode: inviteCode,
          inviterUserId: inviterUserId,
        );
      }
      
    } catch (e) {
      Logger.print('处理群聊邀请失败: $e');
      IMViews.showToast('处理邀请失败，请稍后重试');
    }
  }
    /// 检查群聊支付状态
  Future<Map<String, dynamic>> _checkGroupPaymentStatus(String groupId) async {
    try {
      // 获取群组信息
      final groupInfo = await _getGroupInfo(groupId);
      if (groupInfo == null) {
        return {
          'requiresPayment': false,
          'hasPaid': false,
          'fee': 0.0,
        };
      }
      
      // 从群信息的 ex 字段中解析群收费设置
      bool requiresPayment = false;
      double fee = 0.0;
      
      if (groupInfo.ex != null && groupInfo.ex!.isNotEmpty) {
        try {
          final exData = jsonDecode(groupInfo.ex!);
          if (exData is Map<String, dynamic> && exData.containsKey('groupFee')) {
            final feeData = exData['groupFee'];
            if (feeData is Map<String, dynamic>) {
              requiresPayment = feeData['enabled'] ?? false;
              fee = (feeData['amount'] ?? 0.0).toDouble();
            }
          }
        } catch (e) {
          Logger.print('解析群收费设置失败: $e');
        }
      }
      
      // 如果不需要支付，直接返回
      if (!requiresPayment) {
        return {
          'requiresPayment': false,
          'hasPaid': false,
          'fee': 0.0,
        };
      }
      
      // 检查用户是否已支付
      final hasPaid = await _checkUserPaymentStatus(groupId, OpenIM.iMManager.userID);
      
      return {
        'requiresPayment': requiresPayment,
        'hasPaid': hasPaid,
        'fee': fee,
      };
      
    } catch (e) {
      Logger.print('检查支付状态失败: $e');
      return {
        'requiresPayment': false,
        'hasPaid': false,
        'fee': 0.0,
      };
    }
  }
  
  /// 检查用户是否已支付群费用
  Future<bool> _checkUserPaymentStatus(String groupId, String userId) async {
    try {
      // 这里需要调用后端API检查用户是否已支付该群的费用
      // 示例代码，需要替换为实际的API调用
      await Future.delayed(Duration(milliseconds: 300)); // 模拟网络请求
      
      // 模拟检查逻辑：可以从本地存储或服务器检查支付记录
      // 这里暂时返回 false，表示未支付
      return false;
      
    } catch (e) {
      Logger.print('检查用户支付状态失败: $e');
      return false;
    }
  }
  /// 显示支付页面
  void _showPaymentPage(
    GroupInfo groupInfo,
    String groupId,
    String? inviteCode,
    String? inviterUserId,
    double fee,
  ) {
    AppNavigator.startGroupPayment(
      groupInfo: groupInfo,
      groupId: groupId,
      inviteCode: inviteCode,
      inviterUserId: inviterUserId,
      groupFee: fee,
    );
  }
  /// 直接加入群聊（已支付情况）
  Future<void> _joinGroupDirectly(GroupInfo groupInfo) async {
  try {
    await LoadingView.singleton.wrap(
      asyncFunction: () async {
        await OpenIM.iMManager.groupManager.joinGroup(
          groupID: groupInfo.groupID!,
          reason: '通过邀请链接加入（已支付）',
          joinSource: 2,
        );
        
        IMViews.showToast('加入群聊成功');
        
        // 进入群聊
        final conversationInfo = ConversationInfo(
          conversationID: 'sg_${groupInfo.groupID}',
          conversationType: ConversationType.group,
          userID: '',
          groupID: groupInfo.groupID,
          showName: groupInfo.groupName,
          faceURL: groupInfo.faceURL,
        );
        
        AppNavigator.startChat(conversationInfo: conversationInfo);
      },
    );
  } catch (e) {
    Logger.print('加入群组失败: $e');
    IMViews.showToast('加入群聊失败，请稍后重试');
  }
}
  /// 检查用户是否已登录
  Future<bool> _checkUserLogin() async {
    try {
      final userInfo = await OpenIM.iMManager.userManager.getSelfUserInfo();
      return userInfo.userID?.isNotEmpty == true;
    } catch (e) {
      return false;
    }
  }
  
  /// 获取群组信息
  Future<GroupInfo?> _getGroupInfo(String groupId) async {
    try {
      final groupsInfo = await OpenIM.iMManager.groupManager.getGroupsInfo(
        groupIDList: [groupId],
      );
      return groupsInfo.isNotEmpty ? groupsInfo.first : null;
    } catch (e) {
      Logger.print('获取群组信息失败: $e');
      return null;
    }
  }
  
  /// 检查用户是否已在群组中
  Future<bool> _checkIfAlreadyMember(String groupId) async {
    try {
      final joinedGroups = await OpenIM.iMManager.groupManager.getJoinedGroupList();
      return joinedGroups.any((group) => group.groupID == groupId);
    } catch (e) {
      Logger.print('检查群组成员状态失败: $e');
      return false;
    }
  }
  
  /// 显示需要登录的对话框
  void _showLoginRequiredDialog(String groupId, String? inviteCode, String? inviterUserId) {
    Get.dialog(
      AlertDialog(
        title: const Text('需要登录'),
        content: const Text('请先登录后再加入群聊'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              // 保存邀请信息，登录后自动处理
              _saveInviteInfo(groupId, inviteCode, inviterUserId);
              AppNavigator.startLogin();
            },
            child: const Text('去登录'),
          ),
        ],
      ),
    );
  }
  
  /// 显示已是群成员的对话框
  void _showAlreadyMemberDialog(GroupInfo groupInfo) {
    Get.dialog(
      AlertDialog(
        title: const Text('提示'),
        content: Text('您已经是「${groupInfo.groupName}」的成员了'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('知道了'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              // 修改为正确的方法调用
              AppNavigator.startChat(
                conversationInfo: ConversationInfo(
                  conversationID: groupInfo.groupID!,
                  conversationType: ConversationType.group,
                  userID: '',
                  groupID: groupInfo.groupID,
                  showName: groupInfo.groupName ?? '',
                  faceURL: groupInfo.faceURL ?? '',
                ),
              );
            },
            child: const Text('进入群聊'),
          ),
        ],
      ),
    );
  }
  
  /// 显示加入群组确认对话框
  void _showJoinGroupDialog({
    required GroupInfo groupInfo,
    String? inviteCode,
    String? inviterUserId,
  }) {
    Get.dialog(
      Material(
        color: Colors.transparent,
        child: Center(
          child: Container(
            width: 300.w,
            margin: EdgeInsets.symmetric(horizontal: 32.w),
            decoration: BoxDecoration(
              color: Styles.c_FFFFFF,
              borderRadius: BorderRadius.circular(16.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 20,
                  offset: const Offset(0, 8),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 头部标题
                Container(
                  padding: EdgeInsets.only(top: 24.h, bottom: 16.h),
                  child: Text(
                    '加入群聊',
                    style: Styles.ts_0C1C33_17sp.copyWith(
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
                
                // 群聊信息卡片
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 20.w),
                  padding: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    color: Styles.c_F2F8FF,
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Row(
                    children: [
                      // 群头像
                      Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(12.r),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.08),
                              blurRadius: 8,
                              offset: const Offset(0, 2),
                            ),
                          ],
                        ),
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(12.r),
                          child: ImageUtil.networkImage(
                            url: groupInfo.faceURL ?? '',
                            width: 60.w,
                            height: 60.w,
                            fit: BoxFit.cover,
                            errorWidget: Container(
                              width: 60.w,
                              height: 60.w,
                              decoration: BoxDecoration(
                                color: Styles.c_F2F8FF,
                                borderRadius: BorderRadius.circular(12.r),
                              ),
                              child: Icon(
                                Icons.group,
                                size: 30.w,
                                color: Styles.c_0089FF,
                              ),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 16.w),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              groupInfo.groupName ?? '',
                              style: Styles.ts_0C1C33_10sp.copyWith(
                                fontWeight: FontWeight.w600,
                              ),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                            SizedBox(height: 6.h),
                            Row(
                              children: [
                                Icon(
                                  Icons.people_outline,
                                  size: 14.w,
                                  color: Styles.c_8E9AB0,
                                ),
                                SizedBox(width: 4.w),
                                Text(
                                  '${groupInfo.memberCount ?? 0}人',
                                  style: Styles.ts_8E9AB0_14sp,
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                
                // 提示文字
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
                  child: Text(
                    '确定要加入这个群聊吗？',
                    style: Styles.ts_8E9AB0_14sp,
                    textAlign: TextAlign.center,
                  ),
                ),
                
                // 按钮区域
                Container(
                  padding: EdgeInsets.fromLTRB(20.w, 0, 20.w, 24.h),
                  child: Row(
                    children: [
                      // 取消按钮
                      Expanded(
                        child: GestureDetector(
                          onTap: () => Get.back(),
                          child: Container(
                            height: 44.h,
                            decoration: BoxDecoration(
                              color: Styles.c_F2F8FF,
                              borderRadius: BorderRadius.circular(22.r),
                              border: Border.all(
                                color: Styles.c_E8EAEF,
                                width: 1,
                              ),
                            ),
                            alignment: Alignment.center,
                            child: Text(
                              '取消',
                              style: Styles.ts_0C1C33_17sp_medium.copyWith(
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 12.w),
                      // 加入按钮
                      Expanded(
                        child: GestureDetector(
                          onTap: () {
                            Get.back();
                            _joinGroup(
                              groupInfo: groupInfo,
                              inviteCode: inviteCode,
                              inviterUserId: inviterUserId,
                            );
                          },
                          child: Container(
                            height: 44.h,
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                colors: [
                                  Styles.c_0089FF,
                                  Styles.c_0089FF.withOpacity(0.8),
                                ],
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                              ),
                              borderRadius: BorderRadius.circular(22.r),
                              boxShadow: [
                                BoxShadow(
                                  color: Styles.c_0089FF.withOpacity(0.3),
                                  blurRadius: 8,
                                  offset: const Offset(0, 4),
                                ),
                              ],
                            ),
                            alignment: Alignment.center,
                            child: Text(
                              '加入',
                              style: Styles.ts_FFFFFF_17sp_medium.copyWith(
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
      barrierDismissible: true,
    );
  }
  
  /// 加入群组
  Future<void> _joinGroup({
    required GroupInfo groupInfo,
    String? inviteCode,
    String? inviterUserId,
  }) async {
    try {
      await LoadingView.singleton.wrap(
        asyncFunction: () async {
          // 根据群组类型选择加入方式
          if (groupInfo.needVerification == GroupVerification.directly) {
            // 直接加入
            await OpenIM.iMManager.groupManager.joinGroup(
              groupID: groupInfo.groupID!,
              reason: '通过邀请链接加入',
              joinSource: 2, // 使用数字 2 表示邀请加入
            );
            
            IMViews.showToast('加入群聊成功');
            
            // 进入群聊
            final conversationInfo = ConversationInfo(
              conversationID: 'sg_${groupInfo.groupID}',
              conversationType: ConversationType.group,
              userID: '',
              groupID: groupInfo.groupID,
              showName: groupInfo.groupName,
              faceURL: groupInfo.faceURL,
            );
            
            AppNavigator.startChat(
              conversationInfo: conversationInfo,
            );
          } else {
            // 需要申请
            await OpenIM.iMManager.groupManager.joinGroup(
              groupID: groupInfo.groupID!,
              reason: '通过邀请链接申请加入',
              joinSource: 2,
            );
            
            IMViews.showToast('申请已发送，等待群主审核');
          }
        },
      );
    } catch (e) {
      Logger.print('加入群组失败: $e');
      IMViews.showToast('加入群聊失败，请稍后重试');
    }
  }
  
  /// 保存邀请信息（用于登录后自动处理）
  void _saveInviteInfo(String groupId, String? inviteCode, String? inviterUserId) {
    DataSp.putString('pending_group_invite_id', groupId);
    if (inviteCode != null) {
      DataSp.putString('pending_group_invite_code', inviteCode);
    }
    if (inviterUserId != null) {
      DataSp.putString('pending_group_inviter', inviterUserId);
    }
  }
  
  /// 处理登录后的待处理邀请
  Future<void> processPendingInvite() async {
    final groupId = DataSp.getString('pending_group_invite_id');
    if (groupId?.isNotEmpty == true) {
      final inviteCode = DataSp.getString('pending_group_invite_code');
      final inviterUserId = DataSp.getString('pending_group_inviter');
      
      // 清除保存的邀请信息
      DataSp.remove('pending_group_invite_id');
      DataSp.remove('pending_group_invite_code');
      DataSp.remove('pending_group_inviter');
      
      // 处理邀请
      await _processGroupInvite(
        groupId: groupId!,
        inviteCode: inviteCode,
        inviterUserId: inviterUserId,
      );
    }
  }
  
  /// 生成群聊邀请链接
  static String generateGroupInviteLink({
    required String groupId,
    String? inviteCode,
    String? inviterUserId,
  }) {
    final params = <String, String>{
      'groupId': groupId,
    };
    
    if (inviteCode != null) {
      params['inviteCode'] = inviteCode;
    }
    
    if (inviterUserId != null) {
      params['inviter'] = inviterUserId;
    }
    
    final uri = Uri.https('paxiy.app', '/group/invite', params);
    return uri.toString();
  }
  
  /// 生成自定义scheme链接（用于应用内分享）
  static String generateCustomSchemeLink({
    required String groupId,
    String? inviteCode,
    String? inviterUserId,
  }) {
    final params = <String, String>{
      'groupId': groupId,
    };
    
    if (inviteCode != null) {
      params['inviteCode'] = inviteCode;
    }
    
    if (inviterUserId != null) {
      params['inviter'] = inviterUserId;
    }
    
    final queryString = params.entries
        .map((e) => '${e.key}=${Uri.encodeComponent(e.value)}')
        .join('&');
    
    return 'paxiy://group/invite?$queryString';
  }

  Future<String?> submitGeneratedInviteLink(
    String link,
    String groupId,
    String inviterUserId, {
    String? inviteCode,
  }) async {
    try {
      final url = "${Config.domainBackendUrl}/api/v1/group_invites";
      final resp = await HttpUtil.post(
        url,
        data: {
          'groupId': groupId,
          'inviterUserId': inviterUserId,
          if (inviteCode != null) 'inviteCode': inviteCode,
          'linkUrl': link,
        },
      );
      debugPrint(resp.toString());
      // 兼容 ApiResp 或 success:true 结构
      if (resp is Map) {
          final v = resp['pageUrl'];
          if (v is String && v.isNotEmpty) return v;
          final v2 = resp['page_url'] ?? resp['url'];
          if (v2 is String && v2.isNotEmpty) return v2 as String;
        } else if (resp is String && resp.isNotEmpty) {
          // 兜底：如果后端直接返回字符串
          return resp;
        }
      return null;
    } catch (e) {
      Logger.print('提交邀请链接异常: $e');
      return null;
    }
  }

}